using System;
using System.IO;
using QQZiFramework;
using System.Data;
using QQZiFramework.Membership;
using System.Text.RegularExpressions;
using System.Collections.Generic;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Caching.Memory;
using System.Collections.Specialized;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Configuration.Json;
using QQZiFramework.MQ;
using static NewLife.Remoting.ApiHttpClient;

namespace TestProject1
{
    public class OEMProgram
    {
        string oemName;
        public static Newtonsoft.Json.Linq.JObject appSettingJToken;
        public OEMProgram(string oem)
        {
            oemName = oem;

        }

        static OEMProgram instance;
        public static IServiceCollection serviceCollection;
        public static DBContext CreateDBContext(string oem)
        {
            
            if (instance !=null) return instance.CreateDBContext();
            else
            {
                Console.WriteLine("-------------------" + oem + "-------------");                
                instance=new OEMProgram(oem);
                return  instance.Run(null);

            }
        }


        DBContext Context;

        TokenInfo loginTokenInfo;
        private static IConfiguration _configuration;
        readonly object lockObj=new object();

        public DBContext Run(string[] args)
        {
            lock (lockObj)
            {
                if (_configuration == null)
                {
                    _configuration = new ConfigurationBuilder().AddJsonFile("appsettings.json").Build();

                    appSettingJToken = (Newtonsoft.Json.Linq.JObject)HandlerMemberShip.GetStttingToken();
                    QQZiFramework.DBContextConfig config = new QQZiFramework.DBContextConfig() { EntityTypeFormat = "QQZiCore.Modals.{0},QQZiCore.Modals" };
                    Newtonsoft.Json.Linq.JToken section = appSettingJToken["GlobalDBContextConfig"];
                    if (section != null)
                    {
                        if (section["ProviderName"] != null) config.DatabaseType = section.Value<string>("ProviderName");
                        if (section["LogSql"] != null) config.LogSql = (QQZiFramework.SqlLogMode)Enum.Parse(typeof(QQZiFramework.SqlLogMode), section.Value<string>("LogSql"));
                        else config.LogSql = QQZiFramework.SqlLogMode.All;
                        if (section["AlwayQueryCount"] != null) config.AlwayQueryCount = Convert.ToBoolean(section["AlwayQueryCount"]);
                    }

                    //String permissionFile = Path.Combine(path, "Permission.json");
                    DBContext.LoadConfig(config);
                    //Console.WriteLine(permissionFile);
                    serviceCollection = new ServiceCollection();
                    serviceCollection.AddSingleton<IConfiguration>(_configuration);
                    serviceCollection.AddSingleton<IMemoryCache>(new MyMemoryCache());
                    serviceCollection.UserQQZiFrameworkMQ(_configuration);//要在DBContext.ServiceProvider赋值之前调用
                    DBContext.ServiceProvider = serviceCollection.BuildServiceProvider();
                    DBContext.RegistMembership(new HandlerMemberShip());
                    DBContext.LogDBConfig = null;
                    section = appSettingJToken["Redis"];
                    //VipProfitBLL.Agencys_Redis_Database_Index = DBContext.Default_Redis_Database_Index;
                    //PayAudit.Redis_PAY_Database_Index = PluginBLL.Redis_PAY_Database_Index = section.Value<int>("PAY");
                    //QQZiFramework.MQ.RedisMQ.RedisMQ_DBINDEX = section.Value<int>("MQ");
                    if (section != null)
                    {
                        DBContext.Default_Redis_Database_Index = section.Value<int>("Default");
                        DBContext.DBIdentity_Redis_Database_Index = section.Value<int>("DBIdentity");


                        String redisIp = section.Value<string>("IP");
                        // String redisPort = section.Value<string>("Port");
                        // String redisPassword = section.Value<string>("Password");
                        // int redisPool = section.Value<int>("Pool");
                        // var logDebug = section.Value<bool>("Log");
                        if (!string.IsNullOrEmpty(redisIp))
                        {
                            RedisAccess.SetRedis(section.ToObject<RedisConfig>());
                            // DBContext.SetRedis(redisIp, Convert.ToInt32(redisPort), redisPassword,redisPool,logDebug); 
                        }
                    }



                    // MessageDriver.MessageServer = appSettingJToken.Value<string>("MessageServer");
                    // MessageDriver.ServerDueTime = 12000000;
                    //QQZiCore.Loader.SystemLoader.OnStart( MessageDriver.IsMessageServer, 3);

                    // MessageDriver.RegisterMessageHandle((DBContext context) =>
                    // {
                    //     // TriggerMesageSentAvgs avgs = context.GetArgument<TriggerMesageSentAvgs>("TriggerMesageSentAvgs");
                    //     // DBContext context1 = CreateDBContext();
                    //     // context1.SetArgument("TriggerMesageSentAvgs", avgs);
                    //     // MessageDriver.InvokeServerHandle(context1);
                    // });
                    // QQZiFramework.MQ.IMQDriver mqInstance = QQZiFramework.MQ.MQDriver.GetInstance();

                    // foreach (Type type in MessageDriver.MQ_Consumers)
                    // {
                    //     string queueName = oemName + "_" + type.Name;
                    //     mqInstance.BindReceived(queueName, (value) =>
                    //     {
                    //         int pos = queueName.IndexOf('_');
                    //         string oem = queueName.Substring(0, pos);
                    //         OEMMemberShip memberShip = OEMMemberShip.GetInstance(oem);
                    //         using (DBContext context = memberShip.CreateDBContext())
                    //         {
                    //             BaseBusiness business = context.GetBusiness(type) as BaseBusiness;
                    //             IMQConsumer consumer = business as IMQConsumer;
                    //             consumer.MQ_OnRecive(value);
                    //         }
                    //         return true;
                    //     });
                    // }

                    serviceCollection.UserQQZiFrameworkMQ(_configuration);

                    using (DBContext context = new DBContext())
                    {
                        OEMMemberShip.Init(context);
                    }
                }
            }
            DBContext Context = CreateDBContext();
            return Context;


        }



        public DBContext CreateDBContext()
        {
            if (Context != null) return Context;
            OEMMemberShip memberShip = OEMMemberShip.GetInstance(oemName);
            Context = memberShip.CreateDBContext();
            return Context;
        }

        public static IMQDriver GetMQAccess()
        {
            return QQZiFramework.DBContext.ServiceProvider.GetService(typeof(IMQDriver)) as IMQDriver;
        }





    }



}